/**
 * @author ghostxbh
 * @date 2020/3/4
 * @description
 */
const nodemailer = require('nodemailer');
const mailPortMap = require('../mail_port');

const Mailer = {

    /**
     * 初始化邮箱SMTP服务
     * @param sendData
     * @returns {Mail}
     */
    mailInit(sendData) {
        const {config} = sendData;
        return nodemailer.createTransport({
            host: sendData.host,
            port: Number(sendData.port),
            // secureConnection: sendData.secureConnection ? sendData.secureConnection : false,
            secure: sendData.secure,
            auth: {
                type: 'OAuth2',
                user: sendData.from,
                clientId: config.client_id,
                clientSecret: config.client_secret,
                refreshToken: '1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx',
                accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x',
                expires: 1484314697598
            },
            connectionTimeout: 10000,
        });
    },

    /**
     * Gmail 初始化
     * @param mailParam
     * @returns {Mail}
     */
    gmailInit(mailParam) {
        return nodemailer.createTransport({
            service: 'Gmail',
            auth: {
                user: mailParam.from,
                pass: mailParam.pass,
            },
            connectionTimeout: 5000,
        });
    },

    /**
     * gmail 邮件发送
     * @param sendData
     * @returns {Promise<never>}
     */
    async gmailSend(sendData) {
        let transporter;
        try {
            transporter = this.gmailInit(sendData);
            transporter.verify();
            console.log('gmail inited');
        } catch (e) {
            console.error('gmail init error: ', e);
            return Promise.resolve({code: 1, message: "邮箱初始化失败"});
        }
        if (!utils.verifyMail(sendData.to)) {
            return Promise.resolve({code: 2, message: "发送邮箱不正确"});
        }
        // 填写邮件信息
        const mailOptions = {
            from: sendData.from,
            to: sendData.to,
            cc: sendData.cc || '',
            subject: sendData.subject + sendData.to,
        };
        if (sendData.isHtml) {
            mailOptions.html = sendData.content;
        } else {
            mailOptions.text = sendData.content;
        }
        try {
            let timeout=setTimeout(function () {
                return "aaa";
            },2000);
            let sm= transporter.sendMail(mailOptions).catch(err=>{
                return Promise.resolve({code: 3, message: "邮箱发送失败"});
            });
            return Promise.race([timeout,sm]).then(vs=>{
                if(!vs[1]){
                    return Promise.resolve({code: 3, message: "邮箱发送失败"});
                }else {
                    return Promise.resolve({ code: 200, message: "发送成功" });
                }
            });
        } catch (e) {
            console.error('processSendMail error', e.message);
            return Promise.resolve({code: 3, message: "邮箱发送失败"});
        }
    },

    async sendMail(reqDate) {
        let {from, pass, to, cc = '', subject, content, isHtml = false, config} = reqDate;
        config = (typeof config === 'string' ? JSON.parse(config) : config);
        const host = config ? config.host : `smtp.${utils.getSMTP(from)}.com`;
        const port = config ? config.port : utils.getSMTPPort(from);
        const secure = config ? config.secure : true;
        const connection = {host, port, secure, from, pass, config};
        console.log('mail init config: ', connection);
        let transporter;
        try {
            transporter = await this.mailInit(connection);
            const isInit = await transporter.verify();
            console.log('mail init is success: ', isInit);
        } catch (e) {
            console.error('mail init is error: ', e);
            return Promise.reject('mail init is error: ' + e.message);
        }
        const mailOptions = {from, to, cc, subject};
        if (isHtml) {
            mailOptions.html = content;
        } else {
            mailOptions.text = content;
        }
        try {
            await transporter.sendMail(mailOptions);
            return Promise.resolve();
        } catch (e) {
            console.error('sendMail error', e.message);
            return Promise.reject('sendMail error: ' + e.message);
        }
    },
    /**
     * 处理发送邮件
     * @sendData 发送邮件的内容及参数
     *   --host 主机
     *   --port 端口
     *   --secureConnection 安全连接
     *   --from 发件人string
     *   --pass 授权码
     *   --cc 抄送(非必传)
     *   --to 收件人 string
     *   --subject 主题
     *   --content 邮件内容
     *   --isHtml 内容是否是html(true/false)
     */
    async processSendMail(sendData) {
        const result = {
            success: false,
        };
        // 开启一个SMTP连接
        const transporter = nodemailer.createTransport({
            service: 'Gmail',
            auth: {
                user: sendData.from,
                pass: sendData.pass,
            },
            connectionTimeout: 5000,
        });

        // 填写邮件信息
        const mailOptions = {
            from: sendData.from,
            to: sendData.to,
            cc: sendData.cc || '',
            subject: sendData.subject,
        };
        if (sendData.isHtml) {
            mailOptions.html = sendData.content;
        } else {
            mailOptions.text = sendData.content;
        }
        try {
            await transporter.sendMail(mailOptions);
            result.success = true;
        } catch (e) {
            console.error('processSendMail error', e.message);
            result.message = e.message;
        }
        return result;
    },

    // /**
    //  * 验证是否授权成功
    //  * @sendData 发送邮件的内容及参数
    //  *   --host 主机
    //  *   --port 端口
    //  *   --secureConnection 安全连接
    //  *   --from 发件人string
    //  *   --pass 授权码
    //  */
    // async verifySendMail(sendData) {
    //     const result = {
    //         success: false,
    //     };
    //     // 开启一个SMTP连接
    //     const transporter = nodemailer.createTransport({
    //         host: sendData.host,
    //         port: Number(sendData.port),
    //         secureConnection: sendData.secureConnection ? sendData.secureConnection : false,
    //         secure: Number(sendData.port) === 465,
    //         auth: {
    //             user: sendData.from,
    //             pass: sendData.pass,
    //         },
    //         connectionTimeout: 5000,
    //     });
    //     try {
    //         await transporter.verify();
    //         result.success = true;
    //     } catch (e) {
    //         console.error('verifySendMail error', e.message);
    //         result.message = e.message;
    //     }
    //     return result;
    // }
};

module.exports = Mailer;

const utils = {
    getSMTP(from) {
        if (from.indexOf('@') > -1) {
            const suffix = from.split('@')[1];
            return suffix.split('.')[0];
        } else throw Error('param is Error: [from]');
    },

    getSMTPPort(from) {
        const type = from.split('@')[1].split('.')[0];
        return mailPortMap[`${type}.smtp.ssl`] || mailPortMap[`${type}.smtp`];
    },

    verifyMail(str) {
        let reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
        return reg.test(str);
    }
};
//
// function f() {
//     const msg = {
//         "from": "jenningsleo107@gmail.com",
//         "pass": "4MysJxbuoV",
//         "to": "",
//         "subject": "春天的疫情发展",
//         "content": "guasfjaskj- --q23=-sd@#!@$!@asdaskjldf a,春天疫情发展走势：http://baidu.com?q=疫情发展",
//         "isHtml": false,
//     };
//     Mailer.gmailSend(msg).then(res => console.log(res));
// }
//
// // davidparker8354@gmail.com----AAlvUSbRnj----adelshestovichahdgd@yandex.ru----sgnd7Nd2cae
// f()
